package client;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Date;

import javax.swing.JOptionPane;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import protocal.DataPackage;
import protocal.DataPackage.MessageType;

import com.fasterxml.jackson.databind.ObjectMapper;

import data.User;


public class ChatClient {
	
	private final static Logger logger = LogManager.getLogger(ChatClient.class);
	
	private Socket socket;
	private BufferedReader reader;
	private BufferedWriter writer;
	private static ChatClient imClient;
	
	private ChatClient() throws UnknownHostException, IOException{
			socket = new Socket("127.0.0.1",8003);
			writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
			reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
	}
	
	//singoten ? reconnect?
	public static ChatClient getInstance(){
		if (imClient==null) {
			synchronized (ChatClient.class) {
				if (imClient==null) {
					try {
						imClient = new ChatClient();
					} catch (UnknownHostException e) {
						logger.error(e);
						JOptionPane.showMessageDialog(null, "error happen", "alert", JOptionPane.ERROR_MESSAGE);
						System.exit(0);
					} catch (IOException e) {
						logger.error(e);
						JOptionPane.showMessageDialog(null, "connection fail", "alert", JOptionPane.ERROR_MESSAGE);
						System.exit(0);
					}
				}
			}
		}
		return imClient;
	}
	
	public void close(){
		DataPackage dataPackage = new DataPackage();
		dataPackage.setFromeName(User.name);
		dataPackage.setToName("\\");
		dataPackage.setMessageType(MessageType.LOGOUT);
		dataPackage.setTime(new Date().getTime());
		ObjectMapper mapper = new ObjectMapper();
		try {
			writer.write(mapper.writeValueAsString(dataPackage)+"\n");
			writer.flush();
			Thread.sleep(3000);
			reader.close();
			writer.close();
			socket.close();
		} catch (InterruptedException e) {
			logger.error(e);
		} catch (IOException e) {
			logger.error(e);
		}
		
		
	}

	public BufferedReader getReader() {
		return reader;
	}

	public BufferedWriter getWriter() {
		return writer;
	}
	
	
	
	

}
